/**
 * Created by shantong on 2018/4/29.
 */
import React from 'react';
import { connect } from 'react-redux'
import { Tree, Row, Col, Card, Alert, Form, Input, Icon, TreeSelect, Button, message, Popconfirm } from 'antd';
import { saveMenu, deleteMenu } from '@/api/Api.js'
import { getFormItemLayout, getTailFormItemLayout } from '../../utils/CommonUtil'

const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
const formItemLayout = getFormItemLayout();
const tailFormItemLayout = getTailFormItemLayout();

const mapStateToProps = (state, ownProps) => ({
	menuList: state.common.menuList,
})

const mapDispatchToProps = (dispatch, ownProps) => ({
	// toggleTodo: id => dispatch(toggleTodo(id)),
})

class Meuns extends React.Component {
	constructor(props) {
		super(props);
	}
	state = {
		selectedKeys: [],
		confirmDirty: false,
		menu: {
			id: '',
			action_id: '',
			controller_id: '',
			module_id: 'v1',
			icon: 'bars',
			url: '',
			parent_id: '',
		},
		isLeaf: false,
		addMenuLoading: false,
		saveMenuLoading: false,
	}

	save = (type, e) => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((err, values) => {
			if (err) {
				console.log(err);
				return false;
			}
			if (type === 'add') {
				this.setState({addMenuLoading:true});
			} else {
				this.setState({saveMenuLoading:true});
			}
			saveMenu(type, values).then(result => {
				this.setState({addMenuLoading: false, saveMenuLoading: false});
			});
		});
	}

	deleteMenu = e => {
		if (!this.state.menu.id) {
			message.info('请选择要删除的菜单')
			return false;
		}
		if (!this.state.isLeaf) {
			message.info('该菜单下有子菜单，请先删除子菜单');
			return false;
		}
		deleteMenu(this.state.menu.id).then(result => {
		})
		this.setState({selectedKeys: []});
	}

	onSelect = (selectedKeys, info) => {
		if (selectedKeys.length <= 0) {
			return false;
		}
		let isLeaf = !(!info.node.isLeaf());
		console.log(isLeaf);
		let data = info.selectedNodes[0].props;
		if (data.dataRef) {
			data = data.dataRef;
		}
		let menu = {
			...data,
			url: `v1${data.url}`,
		}
		delete menu.child;
		this.setState({ selectedKeys, menu, isLeaf });
		this.props.form.setFieldsValue(menu);
	}
	renderTreeNodes = (data) => {
		return data.map((item) => {
			if (item.child) {
				return (
					<TreeNode title={item.name} key={item.url} value={item.id} dataRef={item}>
						{this.renderTreeNodes(item.child)}
					</TreeNode>
				);
			}
			item.title = item.name;
			item.key = item.url;
			item.value = item.id;
			return <TreeNode {...item} />;
		});
	}

	/**
	 * 自动生成路由
	 * @param type
	 * @param event
	 */
	handleChangeUrlValue(type, event) {
		let value = event.target.value;
		let menu = this.state.menu;
		menu[ type ] = value;
		this.setState({menu});
		this.handleSetUrl(menu)
	}

	handleSetUrl(menu = false) {
		menu = menu || this.state.menu;
		let moduleId = menu.module_id, controllerId = menu.controller_id, actionId = menu.action_id;
		let url = (moduleId ? `${moduleId}/` : '') + (controllerId ? `${controllerId}` : '') + (actionId ? `/${actionId}` : '');
		this.props.form.setFieldsValue({url})
	}

	handleChangeIcon = e => {
		if (e.target.value == '') {
			return false;
		}
		let menu = this.state.menu;
		menu.icon = e.target.value;
		this.setState({ ...menu });
	}

	handleChangeMenu = value => {
		if (value) {
			let menu = this.state.menu;
			menu.parent_id = value;
			this.setState({ menu });
			this.props.form.setFieldsValue({parent_id: value});
		}
		// this.setState({ value });
	}
	componentDidMount() {
	}

	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<div>
				<Row>
					<Col span={8}>
						<div className="message-box">
							<Card bodyStyle={{padding: '0 24px'}} bordered={false}>
								<Alert style={{margin: '24px 0'}} message="菜单列表" type="info" />
								<Tree
									onSelect={this.onSelect}
									selectedKeys={this.state.selectedKeys}
								>
									{this.renderTreeNodes(this.props.menuList)}
								</Tree>
								<div className="text-right" style={{padding: '24px 0'}}>
									<Popconfirm title="Are you sure delete this menu?" onConfirm={this.deleteMenu} okText="Yes" cancelText="No">
										<Button type="danger" icon="delete" htmlType="button">删除</Button>
									</Popconfirm>
								</div>
							</Card>
						</div>
					</Col>
					<Col span={12}>
						<div className="message-box">
							<Card bodyStyle={{padding: '0 24px'}} bordered={false}>
								<Alert style={{margin: '24px 0'}} message="菜单信息" type="info" />
								<Form>
									<FormItem
										{...formItemLayout}
										label="所属菜单"
									>
										{getFieldDecorator('parent_id', {
											rules: [{
												required: true, message: '请选择所属菜单',
											}],
										})(
											<Input type='hidden' />
										)}
										<TreeSelect
											showSearch
											placeholder="请选择所属菜单"
											// allowClear
											value={this.state.menu.parent_id}
											treeNodeFilterProp='title'
											onChange={this.handleChangeMenu}
										>
											<TreeNode value={0} title="一级菜单" key="/top" />
											{this.renderTreeNodes(this.props.menuList)}
										</TreeSelect>
									</FormItem>
									<FormItem
										{...formItemLayout}
										label="名称"
									>
										{getFieldDecorator('name', {
											rules: [{
												required: true, message: '请输入名称',
											}],
										})(
											<Input />
										)}
									</FormItem>
									<FormItem
										{...formItemLayout}
										label="模块"
									>
										{getFieldDecorator('module_id', {
											rules: [{
												required: true, message: '请输入模块ID',
											}],
											initialValue: 'v1',
										})(<Input onChange={ this.handleChangeUrlValue.bind(this, 'module_id') } />)}
									</FormItem>
									<FormItem
										{...formItemLayout}
										label="控制器"
									>
										{getFieldDecorator('controller_id', {
											rules: [{
											required: true, message: '请输入控制器ID',
										}],
										})(<Input onChange={ this.handleChangeUrlValue.bind(this, 'controller_id') } />)}
									</FormItem>
									<FormItem
										{...formItemLayout}
										label="方法"
									>
										{getFieldDecorator('action_id')
										(
											<Input placeholder="父级菜单为空" onChange={ this.handleChangeUrlValue.bind(this, 'action_id') } />
										)}
									</FormItem>
									<FormItem
										{...formItemLayout}
										label="路由"
									>
										{getFieldDecorator('url', {
											rules: [{
												required: true, message: '请输入路由',
											}],
										})(<Input />)}
									</FormItem>
									<FormItem
										{...formItemLayout}
										label="排序值"
									>
										{getFieldDecorator('sort_value', {
											rules: [{
												required: true, message: '请输入排序值',
											}],
											initialValue: '100',
										})(<Input />)}
									</FormItem>
									<FormItem
										{...formItemLayout}
										label="图标"
									>
										{getFieldDecorator('icon', {
											initialValue: 'bars',
										})(<Input onChange={this.handleChangeIcon} addonAfter={<Icon type={this.state.menu.icon} />} />)}
									</FormItem>
									<span>
										{getFieldDecorator('id', {
											initialValue: '0',
										})(<Input type='hidden' />)}
									</span>

									<FormItem {...tailFormItemLayout}>
										<Button type="success" icon="save" onClick={ this.save.bind(this, 'save') } loading={this.state.saveMenuLoading} style={{marginRight: 10}} htmlType="button">保存</Button>
										<Button type="primary" icon="plus" onClick={ this.save.bind(this, 'add') } loading={this.state.addMenuLoading} htmlType="button">添加为新菜单</Button>
										<p style={{marginBottom: 24}}></p>
									</FormItem>
								</Form>
							</Card>
						</div>
					</Col>
				</Row>
			</div>
		);
	}
}

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(Form.create()(Meuns))